import React, { Component, Fragment } from "react";
// antd
import { Modal, Table, Button, Col, Pagination, Form, Input, message, Select, Tag, Image, Typography } from "antd";
import Action from "@c/buttonAction/Index";
// http
import http from '../../../utils/request';

const { Link } = Typography;
const { Option } = Select;
const { TextArea } = Input;

function ListItem(props) {
    return <div>{props.value}</div>
}

class MiddlewareManage extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "名称", dataIndex: "name", key: "name", width: "220px",
                    render: (text, rowData) => {
                        // var myNameStyle = { marginLeft: "10px", }
                        var myStyle2222 = { display: "float", lineHeight: "25px", textAlign: "left"}

                        return(
                            
                            <div>
                                <div style={myStyle2222}>
                                    <Image
                                        width={22}
                                        src={rowData.logo}
                                    />
                                </div>

                                <div>{rowData.name}</div>
                                <Link target="_blank" href={rowData.domain}>
                                    {rowData.business}-{rowData.code}
                                </Link>
                                
                            </div>
                        )
                    }
                },
                {title: "云平台", dataIndex: "cloud-platform", key: "cloud-platform",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.platform}-{rowData.account_name}</Tag>                                
                            </div>
                        )
                    }
                },
                {title: "部署方式", dataIndex: "deploy", key: "deploy",
                    render: (text, rowData) => {
                        return (
                            <Tag color="gold">{rowData.deploy}</Tag>
                        )
                    }
                },
                {title: "域名", dataIndex: "domain", key: "domain", width: "300px"},
                {title: "地址", dataIndex: "address", key: "address", width: "380px",
                    render: (text, rowData) => {
                        const address = rowData.address.split('\n')
                        const listItems = address.map((item) => 
                                <ListItem key={item.toString()} value={item} />
                        );
                        return (
                            <ul>{listItems}</ul>
                        )
                    }
                },
                {title: "备注", dataIndex: "remark", key: "remark",
                    render: (text, rowData) => {
                        const remark = rowData.remark.split('\n')
                        const listItems = remark.map((item) => 
                                <ListItem key={item.toString()} value={item} />
                        );
                        return (
                            <ul>{listItems}</ul>
                        )
                    }
                },
                {title: "操作", dataIndex: "operation", key: "operation", 
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Action>
                                    <Action.Button onClick={() => this.onEditMiddlewareBtn({rowData: rowData, status: true})}>编辑</Action.Button>
                                    <Action.Button onClick={() => this.onDeleteMiddlewareBtn(rowData)}>删除</Action.Button>
                                </Action>
                            </div>
                        )
                    }           
                }
            ],
            loading: false,
            search_middleware_name: null,
            search_middleware_code: null,
            search_middleware_business: null,
            search_middleware_domain: null,
            search_middleware_address: null,
            visible_add: false,     // 添加
            visible_edit: false,    // 编辑
            visible_delete: false,  // 删除
            middleware_type_id: '',
            middleware_type_name: '',
            visible_edit_id: '',
            visible_edit_name: '',
            visable_edit_code: '',

            label_list_option_name: [],
            middleware_type_list_option_code: [],
            platform_list_option: [],
            account_list_option: [],

        }
        this.formRefAdd = React.createRef();
        this.formRefEdit = React.createRef();
        this.formRefMsg = React.createRef();
    }

    componentDidMount() {
        this.loadData()
        this.loadDataPlatform()
        this.loadDataBusiness()
        this.loadDataMiddlewareType()
    }

    loadDataPlatform = () => {
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/cloud/platform', {params: requestData}).then(response=>{
            const platform_list_option = []
            const resp_data = response.data.data.items
            for (let i = 0; i < resp_data.length; i++) {
                platform_list_option.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            this.setState({
                platform_list_option: platform_list_option
            })
        })
    }

    loadDataMiddlewareType = () => {
        const requestDataBusiness = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/middlewareType', {params: requestDataBusiness}).then(response=>{
            const resp_data = response.data.data.items
            const middleware_type_list_option_code = []
            for (let i = 0; i < resp_data.length; i++) {
                middleware_type_list_option_code.push(<Option key={resp_data[i].code}>{resp_data[i].name}</Option>)
            }
            this.setState({
                middleware_type_list_option_code: middleware_type_list_option_code,
            })
        })
    }

    loadDataBusiness = () => {
        const requestDataBusiness = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/business', {params: requestDataBusiness}).then(response=>{
            const resp_data = response.data.data.items
            const label_list_option_name = []
            for (let i = 0; i < resp_data.length; i++) {
                label_list_option_name.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            this.setState({
                label_list_option_name: label_list_option_name
            })
        })
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'name__contains': this.state.search_middleware_name,
            'domain__contains': this.state.search_middleware_domain,
            'address__contains': this.state.search_middleware_address,
            'code': this.state.search_middleware_code,
            'business': this.state.search_middleware_business,
        }

        // 获取分组列表
        http.get('/middleware', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    // 搜索切换云平台
    onChangePlatform = (value) => {
        if (value) {
            const requestData = {
                'page': 1,
                'limit': 1000,
                'platform': value
            }
    
            http.get('/cloud/account', {params: requestData}).then(response=>{
                const account_list_option = []
                const resp_data = response.data.data.items
                for (let i = 0; i < resp_data.length; i++) {
                    account_list_option.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
                }
                this.setState({
                    account_list_option: account_list_option
                })
            })
        }
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 中间件搜索 */
    onFinishSearch = (data) => {
        this.setState({
            search_middleware_name: data.name ? data.name : null,
            search_middleware_domain: data.domain ? data.domain : null,
            search_middleware_code: data.code ? data.code : null,
            search_middleware_business: data.business ? data.business : null,
            search_middleware_address: data.address ? data.address : null,
        })
        this.loadData()
    }

    /** 添加中间件按钮 */
    onAddMiddlewareBtn = () => {
        this.setState({
            visible_add: true
        })
    }

    /** 添加中间件取消 */
    onFinishAddCancel = () => {
        this.setState({
            visible_add: false
        })
        this.formRefAdd.current.resetFields()
    }

    /** 添加中间件提交 */
    onFinishAdd = (data) => {
        const requestData = {
            name: data.name,
            domain: data.domain,
            address: data.address,
            remark: data.remark,
            business: data.business,
            code: data.code,
            deploy: data.deploy,
            platform: data.platform,
            account_name: data.account_name,
        }
        http.post('/middleware', requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_add: false,
            })
            this.formRefAdd.current.resetFields()
            this.loadData()
        }).catch()
    }

    /** 编辑业务线按钮 */
    onEditMiddlewareBtn = (data) => {
        http.get('/middleware').then(response=>{
            this.formRefEdit.current.setFieldsValue({
                id: data.rowData.id,
                name: data.rowData.name,
                domain: data.rowData.domain,
                address: data.rowData.address,
                remark: data.rowData.remark,
                business: data.rowData.business,
                code: data.rowData.code,
                deploy: data.rowData.deploy,
                platform: data.rowData.platform,
                account_name: data.rowData.account_name,
            })
        }).catch()
 
        this.setState({
            visible_edit: true,
        })
    }

    /** 编辑业务线取消 */
    onFinishEditCancel = () => {
        this.setState({
            visible_edit: false,

        })
        this.formRefEdit.current.resetFields();
    }

    /** 编辑业务线提交 */
    onFinishEdit = (data) => {
        const requestData = {
            name: data.name,
            domain: data.domain,
            address: data.address,
            remark: data.remark,
            business: data.business,
            code: data.code,
            deploy: data.deploy,
            platform: data.platform,
            account_name: data.account_name,
        }
        http.put('/middleware/' + data.id, requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_edit: false
            })
            this.formRefEdit.current.resetFields();
            this.loadData()
        }).catch()
    }

    /** 删除中间件类型提交 */
    handleMiddlewareDelete = () => {
        http.delete('/middleware/' + this.state.middleware_type_id).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_delete: false,
            })
            this.loadData()
        }).catch()    
    }

    /** 删除中间件类型按钮 */
    onDeleteMiddlewareBtn = (data) => {
        this.setState({
            middleware_type_id: data.id,
            middleware_type_name: data.name,
            visible_delete: true
        })
    }

    render(){
        const { loading, dataSource, columns, page, total, visible_add, visible_edit, visible_delete, middleware_type_name,
            middleware_type_list_option_code, label_list_option_name, platform_list_option, account_list_option } = this.state
        const rowSelection = {
            onChange: this.onCheckbox
        }
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch}>
                    <Form.Item label="名称" name="name">
                        <Input placeholder="请输入中间件名称"  />
                    </Form.Item>

                    <Form.Item label="域名" name="domain">
                        <Input placeholder="请输入中间件域名"  />
                    </Form.Item>

                    <Form.Item label="地址" name="address">
                        <Input placeholder="请输入中间件地址"  />
                    </Form.Item>

                    <Form.Item label="标签搜索" name="business">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择区域"
                            optionFilterProp="children"
                            onChange={this.onChangeBusiness}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {label_list_option_name}
                        </Select>
                    </Form.Item>

                    <Form.Item label="类型搜索" name="code">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择区域"
                            optionFilterProp="children"
                            onChange={this.onChangeBusiness}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {middleware_type_list_option_code}
                        </Select>
                    </Form.Item>

                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>
                
                <div style={myStyle1}><Button type="primary" onClick={this.onAddMiddlewareBtn}>添加中间件</Button></div>
                <Table
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 500, x: '70vw' }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Modal
                    title="添加中间件类型"
                    visible={visible_add}
                    onCancel={this.onFinishAddCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width={1000}
                >
                    <Form
                        onFinish={this.onFinishAdd}
                        ref={this.formRefAdd}
                        labelCol={{ span: 3 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <Form.Item label="名称" name="name">
                            <Input></Input>
                        </Form.Item>

                        <Form.Item label="域名" name="domain">
                            <Input></Input>
                        </Form.Item>

                        <Form.Item label="地址" name="address">
                            <TextArea rows={4} maxLength={512} />
                        </Form.Item>

                        <Form.Item label="备注" name="remark">
                            <TextArea rows={4} maxLength={512} />
                        </Form.Item>

                        <Form.Item label="类型" name="code" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择标签"
                                >
                                {middleware_type_list_option_code}
                            </Select>
                        </Form.Item>

                        <Form.Item label="业务" name="business" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择标签"
                                >
                                {label_list_option_name}
                            </Select>
                        </Form.Item>

                        <Form.Item label="部署" name="deploy" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="请选择部署类型"
                                >
                                    <Option key="host">Server</Option>
                                    <Option key="kubernetes">Kubernetes</Option>
                                    <Option key="docker">Docker</Option>
                            </Select>
                        </Form.Item>

                        <Form.Item label="平台" name="platform" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择云平台"
                                onChange={this.onChangePlatform}
                                >
                                {platform_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item label="账户" name="account_name" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择云账户"
                                >
                                {account_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="编辑中间件"
                    visible={visible_edit}
                    onCancel={this.onFinishEditCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width={1000}
                >
                    <Form
                        onFinish={this.onFinishEdit}
                        ref={this.formRefEdit}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <Form.Item label="ID" name="id" hidden>
                            <Input ></Input>
                        </Form.Item>

                        <Form.Item label="名称" name="name">
                            <Input ></Input>
                        </Form.Item>

                        <Form.Item label="域名" name="domain">
                            <Input></Input>
                        </Form.Item>

                        <Form.Item label="地址" name="address">
                            <TextArea rows={4} maxLength={512} />
                        </Form.Item>

                        <Form.Item label="备注" name="remark">
                            <TextArea rows={4} maxLength={512} />
                        </Form.Item>

                        <Form.Item label="类型" name="code" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择标签"
                                >
                                {middleware_type_list_option_code}
                            </Select>
                        </Form.Item>

                        <Form.Item label="业务" name="business" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择标签"
                                >
                                {label_list_option_name}
                            </Select>
                        </Form.Item>

                        <Form.Item label="部署" name="deploy" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="请选择部署类型"
                                >
                                    <Option key="host">Server</Option>
                                    <Option key="kubernetes">Kubernetes</Option>
                                    <Option key="docker">Docker</Option>
                            </Select>
                        </Form.Item>

                        <Form.Item label="平台" name="platform" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择云平台"
                                onChange={this.onChangePlatform}
                                >
                                {platform_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item label="账户" name="account_name" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择云账户"
                                >
                                {account_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="删除类型"
                    visible={visible_delete}
                    onOk={this.handleMiddlewareDelete}
                    onCancel={() => {this.setState({visible_delete: false, middleware_type_id: ''})}}
                    okText="确认"
                    cancelText="取消"
                >
                    <p>确定删除类型<span style={{color: 'red'}}> {middleware_type_name}</span>? 删除后将无法恢复</p>
                </Modal>
            </Fragment>
        )
    }
}
export default MiddlewareManage;